from google.appengine.ext import db
from google.appengine.api import users
import md5

class DataSet(db.Model):
  """ We use DataSet values to divide our data into discrete chunks
  
  Typically, each DataSet corresponds to the data for one user or group
  
  """
  name = db.StringProperty()
  owner = db.UserProperty()
  
  @classmethod
  def create(cls, name, owner):
    key_name = cls.get_key(name, owner)
    dataset = cls(key_name=key_name, name=name, owner=owner)
    dataset.put()
    return dataset
  
  @classmethod
  def get_key(cls, name, owner):
    if isinstance(owner, users.User):
      owner = owner.email()
    return 'k' + md5.new(name + '#' + unicode(owner)).hexdigest()


# Until things are converted to use datasets, we can assign them
# to a default one
DEFAULT_USER = users.User('squirrel.appengine@gmail.com', _auth_domain='gmail.com')
DEFAULT_NAME = 'Default Dataset'
DEFAULT_DATASET_KEY_NAME = DataSet.get_key(DEFAULT_NAME, DEFAULT_USER)
DEFAULT_DATASET = DataSet.get_or_insert(key_name=DEFAULT_DATASET_KEY_NAME,
  name=DEFAULT_NAME,
  user=DEFAULT_USER)
DEFAULT_DATASET_KEY = DEFAULT_DATASET.key()
